<template>
  <div id="echartBox" class="echart-box"></div>
</template>

<script>
import { init } from "echarts";
export default {
  props: {
    title: {
      type: String,
    },
    legend: {
      type: Array,
    },
    options: {
      type: Object,
    },
  },
  methods: {
    drawLine() {
      //   把myChart挂载到this上去
      this.myChart = init(document.getElementById("echartBox"));

      // 指定图表的配置项和数据
      var option = {
        title: {
          top: "25",
          left: "25",
          text: this.title,
        },
        tooltip: {
          trigger: "axis",
        },
        legend: {
          top: "25",
          data: this.legend,
        },
        grid: {
          top: "20%",
          left: "3%",
          right: "4%",
          bottom: "3%",
          containLabel: true,
        },
        toolbox: {
          feature: {
            saveAsImage: {},
          },
        },
        xAxis: {
          type: "category",
          boundaryGap: false,
          data: this.options.xData,
        },
        yAxis: {
          type: "value",
        },
        series: [
          {
            name: "订单数据",
            type: "line",
            data: this.options.yData[0],
          },
          {
            name: "金额数据",
            type: "line",
            data: this.options.yData[1],
          },
        ],
      };

      this.myChart.setOption(option);
    },
    handleSize() {
      this.myChart.resize();
    },
  },
  watch: {
    options: {
      deep: true,
      handler(newValue, oldValue) {
        this.myChart.clear();
        this.drawLine()
      },
    },
  },

  mounted() {
    this.drawLine();
    // 当我们改变窗口大小时 就可以重新绘制
    window.addEventListener("resize", this.handleSize);
  },

  //   在跳转到其他路由 也就是组件销毁前的声明函数
  beforeDestroy() {
    window.removeEventListener("resize", this.handleSize);
  },
};
</script>

<style lang="less" scoped>
.echart-box {
  width: 100%;
  height: 500px;
  margin-top: 40px;
  background-color: #fff;
}
</style>